#!/usr/bin/env python3

'''
Author       : bopo
Date         : 2020-12-08 10:17:37
LastEditors  : bopo
LastEditTime : 2020-12-08 18:26:45
FilePath     : /stealer/stealer/adapter/__init__.py
Description  :
'''

import re

import requests
from unipath import Path
# from tqdm import tqdm

from stealer.logger import log


class BaseAdapter(object):
    link = None
    data = None
    mark = None

    def fetch(self, url: str, output: str = None, stream: bool = True):
        result = self.parse(url=url)
        print('===========================================')
        log.info(result['meta']['headers'])
        print('===========================================')
        self.download(url=result['link'], filename=output, headers=result['meta']['headers'])
        # return self.stream(context={}, index=self.index(self.link)) if stream else result['link']

    def parse(self, url=None, header: bool = True):
        return {
            'name': '',
            'meta': {},
            'link': '',
        }

    def index(self, url):
        index = re.findall(r'(?<=com\/)\w+', url)

        try:
            return index[0]
        except IndexError:
            return None

    def stream(self, context=None, index=None):
        try:
            context['Content-Type'] = 'application/octet-stream'
            context['Content-Disposition'] = f'attachment;filename="{index}.mp4"'
        except Exception as e:
            context = e

        return context

    def download(self, url=None, filename=None, headers=None):
        response = requests.get(url=url, headers=headers)
        # print(response.headers)
        return Path(filename).write_file(response.content, 'wb')

        # response = requests.get(url=url, stream=True, headers=headers)
        # # total = int(response.headers.get('content-length', 0))
        # desc = url.split('/')[-1]
        #
        # with tqdm.wrapattr(open(filename, "wb"), "write", miniters=1, desc=desc, total=int(response.headers.get('content-length', 0))) as buff:
        #     for chunk in response.iter_content(chunk_size=4096):
        #         buff.write(chunk)
        #
        # return True
